<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>websocket调试页面</title>
</head>
<body>
<div style="float: left; padding: 20px">
	<strong>location:</strong> <br/>
	<input type="text" id="serverUrl" size="35" value=""/> <br/>
	<button onclick="connect()">connect</button>
	<button onclick="wsclose()">disConnect</button>
	<br/> <strong>message:</strong> <br/> <input id="txtMsg" type="text" size="50"/>
	<br/>
	<button onclick="sendEvent()">发送</button>
</div>

<div style="float: left; margin-left: 20px; padding-left: 20px; width: 350px; border-left: solid 1px #cccccc;"><strong>消息记录</strong>
	<div style="border: solid 1px #999999;border-top-color: #CCCCCC;border-left-color: #CCCCCC; padding: 5px;width: 100%;height: 172px;overflow-y: scroll;"
		 id="echo-log"></div>
	<button onclick="clearLog()" style="position: relative; top: 3px;">清除消息</button>
</div>

</div>
</body>
<!-- 下面是h5原生websocket js写法 -->
<script type="text/javascript">
	let output;
	let websocket;

	function connect() { //初始化连接
		output = document.getElementById("echo-log")
		let inputNode = document.getElementById("serverUrl");
		let wsUri = inputNode.value;
		try {
			websocket = new WebSocket(wsUri);
		} catch (ex) {
			console.log(ex)
			alert("对不起websocket连接异常")
		}

		connecting();
		window.addEventListener("load", connecting, false);
	}


	function connecting() {
		websocket.onopen = function (evt) {
			onOpen(evt)
		};
		websocket.onclose = function (evt) {
			onClose(evt)
		};
		websocket.onmessage = function (evt) {
			onMessage(evt)
		};
		websocket.onerror = function (evt) {
			onError(evt)
		};
	}

	function sendEvent() {
		let msg = document.getElementById("txtMsg").value
		doSend(msg);
	}

	//连接上事件
	function onOpen(evt) {
		writeToScreen("CONNECTED");
		doSend("WebSocket 已经连接成功！");
	}

	//关闭事件
	function onClose(evt) {
		writeToScreen("连接已经断开！");
	}

	//后端推送事件
	function onMessage(evt) {
		writeToScreen('<span style="color: blue;">服务器: ' + evt.data + '</span>');
	}

	function onError(evt) {
		writeToScreen('<span style="color: red;">异常信息:</span> ' + evt.data);
	}

	function doSend(message) {
		writeToScreen("客户端A: " + message);
		websocket.send(message);
	}

	//清除div的内容
	function clearLog() {
		output.innerHTML = "";
	}

	//浏览器主动断开连接
	function wsclose() {
		websocket.close();
	}

	function writeToScreen(message) {
		let pre = document.createElement("p");
		pre.innerHTML = message;
		output.appendChild(pre);
	}
</script>
</html>
